package cc.cc4414.cc02.core.security;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cc.cc4414.cc02.core.constant.SessionConsts;

/**
 * 认证服务配置
 * 
 * @author cc 2018年6月19日
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

	private static final String CLIENT_ID = "client";
	private static final String CLIENT_SECRET = PasswordEncoderFactories.createDelegatingPasswordEncoder()
			.encode("secret");

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

	@Autowired
	private AuthenticationProvider daoAuthenticationProvider;

	@Bean
	public TokenStore redisTokenStore() {
		return new MyRedisTokenStore(redisConnectionFactory);
	}

	@Bean
	public AuthenticationProvider daoAuthenticationProvider() {
		DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
		daoAuthenticationProvider.setUserDetailsService(userDetailsService);
		return daoAuthenticationProvider;
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.tokenStore(redisTokenStore()).authenticationManager(new AuthenticationManager() {
			@Override
			public Authentication authenticate(Authentication authentication) throws AuthenticationException {
				// 自定义认证逻辑
				// 认证中添加验证码校验逻辑
				// security框架中authentication.getDetails()实际为Map类型，忽略警告
				@SuppressWarnings("unchecked")
				Map<String, String> parameters = (Map<String, String>) authentication.getDetails();
				// 获取传入参数中的验证码
				String captcha = parameters.get("captcha");
				HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
						.getRequest().getSession();
				// 获取session红的验证码
				String sessionCaptcha = (String) session.getAttribute(SessionConsts.CAPTCHA);
				// 一个验证码只能使用一次
				session.removeAttribute(SessionConsts.CAPTCHA);
				// 如果验证码错误，抛出BadCredentialsException异常
				if (captcha == null || !captcha.equalsIgnoreCase(sessionCaptcha)) {
					throw new BadCredentialsException("验证码错误！");
				}
				return daoAuthenticationProvider.authenticate(authentication);
			}
		});
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory().withClient(CLIENT_ID).secret(CLIENT_SECRET).authorizedGrantTypes("refresh_token", "password")
				.scopes("all");
	}
}
